package logic

import (
	"context"
	"fmt"
	"taobao-merchandise/models"

	"taobao-merchandise/taobao_rpc/internal/svc"
	"taobao-merchandise/taobao_rpc/taobao_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductUpdateLogic {
	return &ProductUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductUpdateLogic) ProductUpdate(in *taobao_rpc.ProductUpdateRequest) (*taobao_rpc.ProductUpdateResponse, error) {
	// todo: add your logic here and delete this line
	var product models.Product
	if models.DB.Where("id = ?", in.Id).Limit(1).Find(&product).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if product.ID == 0 {
		return nil, fmt.Errorf("您所修改的商品不存在")
	}
	if product.FromUserId != int(in.FromUser) {
		return nil, fmt.Errorf("您无权修改不属于您的商品")
	}
	product.ProName = in.Name
	product.Image = in.Image
	product.ProPrice = float64(in.Price)
	if err := models.DB.Where("id = ?", in.Id).Updates(&product).Error; err != nil {
		return nil, err
	}
	return &taobao_rpc.ProductUpdateResponse{}, nil
}
